package alt.fr.ma.np.activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.StringTokenizer;

import alt.fr.ma.np.R;
import alt.fr.ma.np.soap.Parameter;
import alt.fr.ma.np.soap.SOAPRequest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

public class AddEventActivity extends CustomTitleActivity {

	private int startYear;
	private int startMonth;
	private int startDay;
	private int startHour;
	private int startMinute;

	private int endYear;
	private int endMonth;
	private int endDay;
	private int endHour;
	private int endMinute;

	static final int START_DATE_DIALOG_ID = 996;
	static final int START_TIME_DIALOG_ID = 997;

	static final int END_DATE_DIALOG_ID = 998;
	static final int END_TIME_DIALOG_ID = 999;

	private EditText startDate;
	private EditText startTime;
	private EditText endDate;
	private EditText endTime;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();

		this.title.setText("Add Event");
		this.title.setCompoundDrawablesWithIntrinsicBounds(
				R.drawable.barrehautaddagendas, 0, 0, 0);
		this.profile.setImageResource(R.drawable.default_profile);

		switch (display.getRotation()) {
		case Surface.ROTATION_0:
			setContentView(R.layout.eventadd);
			break;
		case Surface.ROTATION_90:
			break;
		case Surface.ROTATION_180:
			break;
		case Surface.ROTATION_270:
			break;
		}

		initialize();
	}

	public void initialize() {

		populateEventTypes();
		populateEventStatus();
		populateEventFrequency();

		// Get EditText views
		startDate = (EditText) findViewById(R.id.EventDateFieldFrom);
		startTime = (EditText) findViewById(R.id.EventHourFieldFrom);
		endDate = (EditText) findViewById(R.id.EventDateFieldTo);
		endTime = (EditText) findViewById(R.id.EventHourFieldTo);

		// Initialize Date & Time
		final Calendar c = Calendar.getInstance();
		startYear = c.get(Calendar.YEAR);
		startMonth = c.get(Calendar.MONTH);
		startDay = c.get(Calendar.DAY_OF_MONTH);
		startHour = c.get(Calendar.HOUR_OF_DAY);
		startMinute = c.get(Calendar.MINUTE);
		endYear = startYear;
		endMonth = startMonth;
		endDay = startDay;
		endHour = startHour;
		endMinute = startMinute;

		addListenerOnButtons();
	}

	/**
	 * Fills the event types choice list
	 */
	public void populateEventTypes() {
		String eventTypes = "";

		try {
			eventTypes = getEventTypes();
		} catch (InterruptedException e) {
			Log.d("ERROR - SOAPRequest", "InterruptedException", e);
		}

		Log.d("NORMAL - AddEventActivity", "SOAPResponse = " + eventTypes);

		StringTokenizer tokenizer = new StringTokenizer(eventTypes, ";");

		Spinner spinner = (Spinner) findViewById(R.id.EventSpinnerFieldType);

		spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				Object item = parent.getItemAtPosition(pos);
				Log.d("NORMAL - AddEventActivity",
						"Choice EventType = " + item.toString());
				populatePlaces(item.toString());
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);

		spinner.setAdapter(adapter);

		while (tokenizer.hasMoreTokens()) {
			adapter.add(tokenizer.nextToken());
		}
	}

	public void populatePlaces(String eventType) {
		String places = "";

		try {
			places = getPlaces(eventType);
		} catch (InterruptedException e) {
			Log.d("ERROR - SOAPRequest", "InterruptedException", e);
		}

		Log.d("NORMAL - AgendaActivity", "SOAPResponse = " + places);

		StringTokenizer tokenizer = new StringTokenizer(places, ";");

		Spinner spinner = (Spinner) findViewById(R.id.EventSpinnerFieldPlaces);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);

		spinner.setAdapter(adapter);

		while (tokenizer.hasMoreTokens()) {
			adapter.add(tokenizer.nextToken());
		}
	}

	public void populateEventStatus() {
		Spinner spinner = (Spinner) findViewById(R.id.EventSpinnerFieldStatut);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);

		spinner.setAdapter(adapter);

		adapter.add("Public");
		adapter.add("Private");
	}

	public void populateEventFrequency() {
		Spinner spinner = (Spinner) findViewById(R.id.EventSpinnerFieldFrequency);

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item);

		spinner.setAdapter(adapter);

		adapter.add("Occasional");
		adapter.add("Daily");
		adapter.add("Weekly");
		adapter.add("Monthly");
		adapter.add("Annualy");
	}

	/**
	 * WebService to fetch event types
	 * 
	 * @return the list of event types
	 * @throws InterruptedException
	 */
	public String getEventTypes() throws InterruptedException {

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		String login = preferences.getString("login", null);
		String password = preferences.getString("password", null);

		ArrayList<Parameter> params = new ArrayList<Parameter>();
		Parameter action = new Parameter("sAction", "FetchEventTypes");
		Parameter actionParams = new Parameter("sParams", "");
		params.add(action);
		params.add(actionParams);

		SOAPRequest SOAPRequest = new SOAPRequest("sociablon", login, password,
				"WSSociablonWebService", params);

		Thread request = new Thread(SOAPRequest);
		request.start();
		request.join();

		try {
			return SOAPRequest.getSOAPResponse();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return password;
	}

	/**
	 * WebService to fetch existing places
	 * 
	 * @return the list of existing places
	 * @throws InterruptedException
	 */
	public String getPlaces(String eventType) throws InterruptedException {

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		String login = preferences.getString("login", null);
		String password = preferences.getString("password", null);

		ArrayList<Parameter> params = new ArrayList<Parameter>();
		Parameter action = new Parameter("sAction", "FetchPlaces");
		Parameter actionParams = new Parameter("sParams", eventType);
		params.add(action);
		params.add(actionParams);

		SOAPRequest SOAPRequest = new SOAPRequest("sociablon", login, password,
				"WSSociablonWebService", params);

		Thread request = new Thread(SOAPRequest);
		request.start();
		request.join();

		try {
			return SOAPRequest.getSOAPResponse();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return password;
	}

	public void addListenerOnButtons() {
		startDate.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(START_DATE_DIALOG_ID);
				return true;
			}
		});

		startTime.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(START_TIME_DIALOG_ID);
				return true;
			}
		});

		endDate.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(END_DATE_DIALOG_ID);
				return true;
			}
		});

		endTime.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				showDialog(END_TIME_DIALOG_ID);
				return true;
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case START_DATE_DIALOG_ID:
			return new DatePickerDialog(this, startDatePickerListener,
					startYear, startMonth, startDay);
		case START_TIME_DIALOG_ID:
			return new TimePickerDialog(this, startTimePickerListener,
					startHour, startMinute, true);
		case END_DATE_DIALOG_ID:
			return new DatePickerDialog(this, endDatePickerListener, endYear,
					endMonth, endDay);
		case END_TIME_DIALOG_ID:
			return new TimePickerDialog(this, endTimePickerListener, endHour,
					endMinute, true);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener startDatePickerListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			startYear = selectedYear;
			startMonth = selectedMonth;
			startDay = selectedDay;
			setDate(startDate, startYear, startMonth, startDay);
		}
	};

	private TimePickerDialog.OnTimeSetListener startTimePickerListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int selectedHourOfDay,
				int selectedMinute) {
			startHour = selectedHourOfDay;
			startMinute = selectedMinute;
			setTime(startTime, startHour, startMinute);
		}

	};

	private DatePickerDialog.OnDateSetListener endDatePickerListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			endYear = selectedYear;
			endMonth = selectedMonth;
			endDay = selectedDay;
			setDate(endDate, endYear, endMonth, endDay);
		}
	};

	private TimePickerDialog.OnTimeSetListener endTimePickerListener = new TimePickerDialog.OnTimeSetListener() {

		public void onTimeSet(TimePicker view, int selectedHourOfDay,
				int selectedMinute) {
			endHour = selectedHourOfDay;
			endMinute = selectedMinute;
			setTime(endTime, endHour, endMinute);
		}

	};

	public void setDate(EditText view, int year, int month, int day) {
		view.setText(new StringBuilder().append(month + 1).append("-")
				.append(day).append("-").append(year));
	}

	public void setTime(EditText view, int hourOfDay, int minute) {
		view.setText(new StringBuilder().append(hourOfDay).append(":")
				.append(minute));
	}

	public void publishAction(View view) {
		switch (view.getId()) {
		case R.id.buttonSave:
			String response = "";
			try {
				response = publishEvent();
			} catch (InterruptedException e) {
				Log.d("ERROR - AddEventActivity", "Error = " + e.getMessage());
			}
			
			//TODO Change to AsynchTask !!!
			AlertDialog alertDialog = new AlertDialog.Builder(
					AddEventActivity.this).create();
			alertDialog.setTitle("Publish Event");
			alertDialog.setIcon(R.drawable.barrehautaddagendas);

			if (response.charAt(0) == '1')
				alertDialog
						.setMessage("Your event was successfully published!");
			else
				alertDialog.setMessage("An error occured!");

			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(AddEventActivity.this, AgendaActivity.class));
					finish();
				}
			});
			alertDialog.show();
			break;
		}
	}

	/**
	 * WebService to publish the event
	 * 
	 * @return Result of the WS call
	 * @throws InterruptedException
	 */
	public String publishEvent() throws InterruptedException {

		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(this);

		String login = preferences.getString("login", null);
		String password = preferences.getString("password", null);

		ArrayList<Parameter> params = new ArrayList<Parameter>();

		// Fetch all parameters from the view!!!
		String eventInformation = "";

		// Fetching event name
		eventInformation += ((EditText) findViewById(R.id.EventTextDefaultFieldObjet))
				.getText() + "|";
		eventInformation += ((Spinner) findViewById(R.id.EventSpinnerFieldType))
				.getSelectedItem().toString() + "|";
		eventInformation += startDate.getText() + "|";
		eventInformation += startTime.getText() + "|";
		eventInformation += endDate.getText() + "|";
		eventInformation += endTime.getText() + "|";
		eventInformation += ((Spinner) findViewById(R.id.EventSpinnerFieldPlaces))
				.getSelectedItem().toString() + "|";
		eventInformation += ((EditText) findViewById(R.id.EventTextDefaultFieldDescription))
				.getText() + "|";
		eventInformation += ((Spinner) findViewById(R.id.EventSpinnerFieldStatut))
				.getSelectedItem().toString() + "|";
		eventInformation += ((Spinner) findViewById(R.id.EventSpinnerFieldFrequency))
				.getSelectedItem().toString();

		params.add(new Parameter("sAction", "PublishEvent"));
		params.add(new Parameter("sParams", eventInformation));

		SOAPRequest SOAPRequest = new SOAPRequest("sociablon", login, password,
				"WSSociablonWebService", params);

		Thread request = new Thread(SOAPRequest);
		request.start();
		request.join();

		try {
			return SOAPRequest.getSOAPResponse();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return eventInformation;
	}
	
	public void cancelAction(View view) {
		finish();
	}
}
